package com.tianluo.tianluobookstore.task;

import com.tianluo.tianluobookstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StopWatch;
import java.util.Date;

@Component
@EnableScheduling // 启用定时任务
public class OrderCancelSchedule {

    @Autowired
    private OrderService orderService;

    // 分页大小（建议根据性能调整）
    private static final int PAGE_SIZE = 100;

    /**
     * 每20分钟执行一次（cron表达式可配置）
     * fixedDelay: 上次执行结束后间隔时间
     */
    @Scheduled(cron = "0 */20 * * * ?") // 支持动态配置：@Scheduled(cron = "${schedule.order.cancel}")
    public void cancelTimeoutOrders() {
        StopWatch watch = new StopWatch();
        watch.start();

        // 1. 计算超时时间（30分钟前）
        Date timeoutTime = new Date(System.currentTimeMillis() - 30 * 60 * 1000);
        int totalCancel = 0;
        int currentPage = 1;
        boolean hasMore;

        do {
            // 2. 分页查询并处理订单取消
            hasMore = orderService.processTimeoutOrders(timeoutTime, currentPage, PAGE_SIZE);

            if (hasMore) {
                currentPage++;
                totalCancel += PAGE_SIZE;
            }
        } while (hasMore);

        watch.stop();
        System.out.printf("[定时任务] 取消超时订单完成，共处理%d条，耗时%dms%n",
                totalCancel, watch.getLastTaskTimeMillis());
    }
}